#!/usr/bin/env python3
"""
Simple log viewer for InCloud MCP Server
"""
import os
import glob
import argparse
from datetime import datetime

def view_logs(log_dir="logs", lines=50, follow=False, filter_text=None):
    """View log files"""
    
    if not os.path.exists(log_dir):
        print(f"❌ Log directory '{log_dir}' not found")
        return
    
    # Find log files
    log_files = glob.glob(os.path.join(log_dir, "*.log"))
    
    if not log_files:
        print(f"❌ No log files found in '{log_dir}'")
        return
    
    # Sort by modification time (newest first)
    log_files.sort(key=os.path.getmtime, reverse=True)
    
    print("📁 Available log files:")
    for i, log_file in enumerate(log_files, 1):
        size = os.path.getsize(log_file)
        mtime = datetime.fromtimestamp(os.path.getmtime(log_file))
        print(f"   {i}. {os.path.basename(log_file)} ({size} bytes, {mtime.strftime('%Y-%m-%d %H:%M:%S')})")
    
    # Use the newest log file
    latest_log = log_files[0]
    print(f"\n📖 Viewing: {latest_log}")
    print("=" * 80)
    
    try:
        with open(latest_log, 'r', encoding='utf-8') as f:
            if follow:
                # Follow mode (like tail -f)
                print("🔄 Following log file (Ctrl+C to stop)...")
                f.seek(0, 2)  # Go to end of file
                
                try:
                    while True:
                        line = f.readline()
                        if line:
                            if filter_text is None or filter_text.lower() in line.lower():
                                print(line.rstrip())
                        else:
                            import time
                            time.sleep(0.1)
                except KeyboardInterrupt:
                    print("\n⏹️  Stopped following log file")
            else:
                # Show last N lines
                all_lines = f.readlines()
                
                if filter_text:
                    filtered_lines = [line for line in all_lines if filter_text.lower() in line.lower()]
                    display_lines = filtered_lines[-lines:] if len(filtered_lines) > lines else filtered_lines
                    print(f"🔍 Showing last {len(display_lines)} lines (filtered by '{filter_text}'):")
                else:
                    display_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines
                    print(f"📄 Showing last {len(display_lines)} lines:")
                
                print("-" * 80)
                for line in display_lines:
                    print(line.rstrip())
                
                if len(all_lines) > lines and not filter_text:
                    print("-" * 80)
                    print(f"📊 Total lines in file: {len(all_lines)}")
                    print(f"💡 Use --lines {len(all_lines)} to see all lines")
    
    except Exception as e:
        print(f"❌ Error reading log file: {e}")

def main():
    parser = argparse.ArgumentParser(description="View InCloud MCP Server logs")
    parser.add_argument("--dir", default="logs", help="Log directory (default: logs)")
    parser.add_argument("--lines", "-n", type=int, default=50, help="Number of lines to show (default: 50)")
    parser.add_argument("--follow", "-f", action="store_true", help="Follow log file (like tail -f)")
    parser.add_argument("--filter", help="Filter lines containing this text")
    
    args = parser.parse_args()
    
    print("🔍 InCloud MCP Server Log Viewer")
    print("=" * 40)
    
    view_logs(
        log_dir=args.dir,
        lines=args.lines,
        follow=args.follow,
        filter_text=args.filter
    )

if __name__ == "__main__":
    main()
